//
//  DMHttpManager.m
//  DMHttpManager
//
//  Created by zgy on 2025/6/30.
//

#import "DMHttpManager.h"
#import <AFNetworking/AFNetworking.h>
#import "DMApiEncryptor.h"


@interface DMHttpManager ()


@property (nonatomic, strong) DMApiEncryptor *encryptor;
@property (nonatomic,   copy) NSString *gatewayToken;

@end

@implementation DMHttpManager


static DMHttpManager *_instance;
+ (id)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [super allocWithZone:zone];
    });
    
    return _instance;
}

+ (instancetype)shared
{
    if (_instance == nil) {
        _instance = [[DMHttpManager alloc] init];
    }
    return _instance;
}


#pragma mark- 网关2.0 请求

- (void)postAction:(NSString *)action dataParams:(NSDictionary *)dataParams completion:(void (^)(NSDictionary *response, NSError *error))completion
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    // zgytodo
    [manager POST:@"https://sit-pxapi.yundasys.com/gateway/interface"
       parameters:[self transformReqParams:dataParams action:action isEncrypt:NO]
          headers:[self getReqHeaders]
         progress:nil
          success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"成功: %@", responseObject);
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *responseDict = (NSDictionary *)responseObject;
            if ([responseDict[@"success"] boolValue]) {
                if ([dataParams[@"_cacheToken"] boolValue]) {
                    self.gatewayToken = responseDict[@"body"][@"token"];
                    self.encryptor = nil;
                }
            }
        }
        
        if (completion) {
            completion(responseObject, nil);
        }
            
        
        
    }
          failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"失败: %@", error);
        
        if (completion) {
            completion(nil, error);
        }
    }];
    
}

- (void)postEncryptedAction:(NSString *)action dataParams:(NSDictionary *)dataParams completion:(void (^)(NSDictionary *response, NSError *error))completion
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
   
    // zgytodo
    [manager POST:@"https://sit-pxapi.yundasys.com/gateway/interface"
       parameters:[self transformReqParams:dataParams action:action isEncrypt:YES]
          headers:[self getReqHeaders]
         progress:nil
          success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"加密接口成功: %@", responseObject);
        
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *responseDict = (NSDictionary *)responseObject;
            if ([responseDict[@"success"] boolValue]) {
                NSString *tmp0 = responseDict[@"body"];
                NSString *tmp1 = [self.encryptor decrypt3DES:tmp0];
                NSLog(@"%@", tmp1);
            }
        }
        
    }
          failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"加密接口失败: %@", error);
    }];
}

- (void)postAction:(NSString *)action dataParams:(NSDictionary *)dataParams encrypted:(BOOL)encrypted completion:(void (^)(NSDictionary *response, NSError *error))completion
{
    if (encrypted) {
        [self postEncryptedAction:action dataParams:dataParams completion:completion];
    }else {
        [self postAction:action dataParams:dataParams completion:completion];
    }
}

#pragma mark-
- (NSDictionary *)transformReqParams:(NSDictionary *)oldDic action:(NSString *)action isEncrypt:(BOOL)isEncrypt
{
    if (!oldDic) {
        oldDic = @{};
    }
    NSMutableDictionary *tmpOld = [NSMutableDictionary dictionaryWithDictionary:oldDic];
    
    BOOL option = NO;
    if (tmpOld[@"option"]) {
        option = [tmpOld[@"option"] boolValue];
        [tmpOld removeObjectForKey:@"option"];
    }
    
    
    NSString *encryptedData = nil;
    if (isEncrypt) {
        NSString *str = [self dictToJsonString:tmpOld];
        encryptedData = [self.encryptor encrypt3DES:str];
    }
    
    
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    long long timeStamp = (long long)(time * 1000);
    NSMutableDictionary *tmp =  @{
        @"version": @"V1.0",
        @"phoenixVersion": @"1.1",
        @"option": @(option),
        @"action": action,
        @"appid": @"eqpgizo3nxiygvna", // zgytodo
        @"appver": @"5.52.0.1", // zgytodo
        @"req_time": @(timeStamp),
        @"data": tmpOld
    }.mutableCopy;
    
    if (encryptedData) {
        tmp[@"data"] = encryptedData;
    }
    
    if (option) {
        tmp[@"userId"] = @(timeStamp);
    }
    
    if (self.gatewayToken) {
        tmp[@"token"] = self.gatewayToken;
    }
    
    
    return tmp;
    
}

- (NSDictionary *)getReqHeaders
{
    // zgytodo
    /**
     deviceType: iPhone 6s
     phn: 191****3333
     bddriverToken: 5d9bec23-292a-4c31-be26-f44a3ad1ec41
     appVersion: 5.52.0.1
     deviceInfo: iPhone/iPhone 6s/iOS 15.8.3
     deviceCode: 58D43AC6-2366-4B59-8FFC-6AA51CDBF730
     appId: eqpgizo3nxiygvna
     */
    return @{
        @"appId": @"eqpgizo3nxiygvna",
        @"appVersion": @"5.52.0.1",
        @"deviceInfo": @"iPhone/iPhone 6s/iOS 15.8.3",
    };
}


- (DMApiEncryptor *)encryptor
{
    if (nil == _encryptor) {
        _encryptor = [[DMApiEncryptor alloc] initWithToken:_gatewayToken appID:@"eqpgizo3nxiygvna"]; // zgytodo
    }
    return _encryptor;
}

#pragma mark- helpers
- (NSString *)dictToJsonString:(NSDictionary *)dict
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
    NSString *jsonString = nil;
    if (!error && jsonData) {
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    
    return jsonString;
}

- (NSDictionary *)jsonStringToDict:(NSString *)jsonString
{
    if (!jsonString || jsonString.length == 0) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error;
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
    if (error) {
        return nil;
    }
    return dict;
}


@end
